package model

import (
	"base-web/global"
	"github.com/jinzhu/gorm"
	"time"
)

// User [...]
type UserModel struct {
	ID        int    `json:"id" gorm:"primary_key;column:id;type:int(10) unsigned;not null"`
	Name      string `json:"name" gorm:"index:name_sex_age_index;column:name;type:varchar(100)"`
	Sex       string `json:"sex" gorm:"index:name_sex_age_index;column:sex;type:varchar(100)"`
	Age       int    `json:"age" gorm:"index:name_sex_age_index;column:age;type:int(11)"`
	Phone     int    `json:"phone" gorm:"index:name_sex_age_index;column:phone;type:varchar(11)"`
	UpdatedAt int64  `json:"-" gorm:"column:updated_at;type:int(50)"`
	CreatedAt int64  `json:"-" gorm:"column:created_at;type:int(50)"`
}

// GetTableName get sql table name.获取数据库名字
func (obj *UserModel) GetTableName() string {
	return "user"
}

//创建之前
func (obj *UserModel) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("updated_at", time.Now().Unix())
	scope.SetColumn("created_at", time.Now().Unix())
	return nil
}

//保存之前
func (obj *UserModel) BeforeSave(scope *gorm.Scope) error {
	scope.SetColumn("updated_at", time.Now().Unix())
	return nil
}

//更新之前
func (obj *UserModel) BeforeUpdate(scope *gorm.Scope) error {
	scope.SetColumn("updated_at", time.Now().Unix())
	return nil
}

// Get 获取
func (obj *UserModel) Get() (result UserModel, err error) {
	err = global.BASE_DB.Table(obj.GetTableName()).Find(&result).Error
	return
}

// WithPhone phone获取
func (obj *UserModel) WithPhone() (result UserModel, err error) {
	err = global.BASE_DB.Table(obj.GetTableName()).Where("phone = ?", obj.Phone).Find(&result).Error
	return
}

// Gets 获取批量结果
func (obj *UserModel) Gets() (results []*UserModel, err error) {
	err = global.BASE_DB.Table(obj.GetTableName()).Find(&results).Error
	return
}

//新增一个用户
func (obj *UserModel) Create() (err error) {
	err = global.BASE_DB.Table(obj.GetTableName()).Create(&obj).Error
	return
}
